from django.shortcuts import render
from django.contrib.auth import get_user_model, login, logout
from django.views.generic import View, FormView, TemplateView
from django.shortcuts import redirect, render, reverse
from django.conf import settings
from user.forms import LogInViaEmailForm, LoginViaUsernameForm, RegisterForm
from rest_framework import viewsets
from user.serializers import UserInformationSerializers


class UserInformationViewSets(viewsets.ModelViewSet):
    queryset = get_user_model().objects.all()
    serializer_class = UserInformationSerializers


class GuestOnlyView(View):
    def dispatch(self, request, *args, **kwargs):
        username = request.session.get('name')
        if username:
            return redirect(settings.LOGIN_REDIRECT_URL)
        return super().dispatch(request, *args, **kwargs)


class LogInViaEmailView(GuestOnlyView, FormView):
    template_name = 'login.html'

    def get(self, request, *args, **kwargs):
        loginviausername = 0
        form = self.get_form_class()
        return render(request, 'login.html', locals())

    def get_form_class(self):
        return LogInViaEmailForm

    def form_valid(self, form):
        request = self.request
        loginviausername = 0
        form = self.get_form_class()
        result, message, username = self.login_l()
        if result:
            name = username
            log_out = '注销'
            return render(request, 'index.html', locals())
        else:
            log_in = '登录'
            return render(request, 'login.html', locals())

    def login_l(self):
        res = self.request
        email = res.POST.get('email')
        password = res.POST.get('password')
        print(email, type(email), password)
        u = get_user_model()
        try:
            user = u.objects.get(email=email)
            print(user.username, user.password, '3')
            print(user.backend)
            if user.password == password:
                # 存储session
                message = "登陆成功！"
                res.session['name'] = user.username
                login(res, user, backend=settings.AUTHENTICATION_BACKENDS[0])
                # return redirect('/')
                return True, message, user.username
            else:
                message = "密码不正确！"
                return False, message, None
        except:
            message = "邮箱不存在！"
        return False, message, None


class LogInViaUsernameView(GuestOnlyView, FormView):
    template_name = 'login.html'

    def get(self, request, *args, **kwargs):
        loginviausername = 1
        form = self.get_form_class()
        return render(request, 'login.html', locals())

    def get_form_class(self, **kwargs):
        return LoginViaUsernameForm

    def form_valid(self, form):
        request = self.request
        loginviausername = 1
        form = self.get_form_class()
        result, message = self.login_l()
        if result:
            print('login_result:', result)
            name = request.POST.get('username')
            log_out = '注销'
            return render(request, 'index.html', locals())
        else:
            print('login_result:', result)
            log_in = '登录'
            return render(request, 'login.html', locals())

    def login_l(self):
        res = self.request
        username = res.POST.get('username')
        password = res.POST.get('password')
        # print(username, type(username), password)
        u = get_user_model()
        try:
            user = u.objects.get(username=username)
            # print(user.username, user.password, '3')
            if user.password == password:
                # 存储session
                message = "登陆成功！"
                login(res, user, backend=settings.AUTHENTICATION_BACKENDS[0])
                res.session['name'] = username
                return True, message
            else:
                message = "密码不正确！"
                return False, message
        except:
            message = "用户名不存在！"
        return False, message


class RegisterView(GuestOnlyView, FormView):
    template_name = 'register.html'
    form_class = RegisterForm

    def form_valid(self, form):
        print('1')
        request = self.request
        user_model = get_user_model()
        user = user_model()
        user.email = request.POST.get('email')
        user.username = request.POST.get('username')
        user.set_password(request.POST.get('password1'))
        user.save()
        log_in = '登录'
        register_success_message = '注册成功，点击登录按钮即可登录！'
        return render(request, 'index.html', locals())

        # return redirect(settings.LOGIN_REDIRECT_URL)

    # def get(self, request, *args, **kwargs):
    #     form = self.form_class
    #     return render(request, 'index.html', locals())


class IndexView(View):
    def get(self, request):
        name = request.session.get('name', '游客')
        log_in = '登录'
        if name != '游客':
            log_out = '注销'
            log_in = None
        return render(request, 'index.html', locals())


class LogOutView(View):
    def get(self, request):
        logout(request)
        log_in = '登录'
        name = request.session.get('name', '游客')
        return render(request, 'index.html', locals())
